package com.sunchangming.stmdb.helper;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.google.protobuf.CodedInputStream;
import com.google.protobuf.CodedOutputStream;

public class NameDirectorySer implements Serializer {

	@SuppressWarnings("unchecked")
	@Override
	public byte[] serialize(Object obj) throws IOException {
		final Map<String, Long> data = (Map<String, Long>) obj;
		int size = CodedOutputStream.computeInt32SizeNoTag(data.size());
		for (final Map.Entry<String, Long> e : data.entrySet()) {
			size += CodedOutputStream.computeStringSizeNoTag(e.getKey());
			size += CodedOutputStream.computeInt64SizeNoTag(e.getValue());
		}
		final byte[] ret = new byte[size];
		final CodedOutputStream cos = CodedOutputStream.newInstance(ret);
		cos.writeInt32NoTag(data.size());
		for (final Map.Entry<String, Long> e : data.entrySet()) {
			cos.writeStringNoTag(e.getKey());
			cos.writeInt64NoTag(e.getValue());
		}

		//这句代码其实不必要
		cos.flush();

		return ret;
	}

	@Override
	public Object deserialize(byte[] serialized) throws IOException {
		final CodedInputStream cis = CodedInputStream.newInstance(serialized);
		final int size = cis.readInt32();
		final Map<String, Long> data = new HashMap<String, Long>(size);
		for (int i = 0; i != size; ++i) {
			final String key = cis.readString();
			final long value = cis.readInt64();
			data.put(key, value);
		}
		return data;
	}

}
